#include "GetFileList.h"
#include "FileUtils.h"
#include "ConfigReader.h"
#include "NodeHandler.h"
#include <list>
#include <iostream>
#include "net_tool.h"
#include <vector>
#include <string.h>
#include "globalinfo.h"
namespace task {
    int GetFileList::clientAction(socketinf masterSockInf, const char * arg, size_t len) {
        globalInfo.remoteFileList.clear();
        DataFrame dataFrame;
        dataFrame.sendFrame(masterSockInf.socket_fd, TaskFlag::getfilelist, 0);
        dataFrame.readFrame(masterSockInf.socket_fd);
        FILE * fp = fdopen(masterSockInf.socket_fd, "r");
        unsigned long long recv_cnt = 0;
        char buffer[8192];
        FileInfo fileinfo;
        unsigned long long total_size = 0;
        size_t recv_len = 0;
        while ( recv_cnt < dataFrame.length )
        {
            fgets(buffer, 8191, fp);
            recv_len = strlen(buffer);
            recv_cnt += recv_len;
            buffer[recv_len - 1] = 0;
            FileInfo::parse(buffer, fileinfo);
            total_size += fileinfo.size;
            globalInfo.remoteFileList.push_back(fileinfo);
        }
        std::cout << "Remote files total count : " << globalInfo.remoteFileList.size() << std::endl;
        std::cout << "Remote files total size  : " << FileUtils::toSizeString(total_size) << std::endl;
        std::cout << "Update remote files list cache finish" << std::endl;
        return AUTO_CLOSE;
    }
    int GetFileList::serverAction(socketinf slaveSockInf, unsigned long long dataLength) {
        DataFrame dataFrame;
        auto res = FileUtils::traverseDir(configReader.getConfig(CONFIG_RESOURCE_DIR, CONFIG_RESOURCE_DIR_DEFAULT).c_str());
        std::string data;
        for(auto i = res.begin(); i != res.end(); i++) {
            data += i->toString();
            data += '\n';
        }
        size_t len = data.length();
        size_t sended = 0;
        size_t surplus;
        int cnt;
        dataFrame.sendFrame(slaveSockInf.socket_fd, 0xff, len);
        while ( sended < len ) {
            surplus = len - sended;
            cnt = send(slaveSockInf.socket_fd, data.c_str() + sended, surplus > 8192 ? 8192 : surplus, 0);
            if (cnt <= 0) {
                throw SocketException("Send error");
            }
            sended += cnt;
        }
        return AUTO_CLOSE;
    }
}